import '../../css/department/AddEdit.scss'
import { Cascader, Form, Input, Button, message } from 'antd';
import { useEffect, useState,useRef } from 'react';
import { departmentList, departmentAdd,departmentEdit,departmentShow } from '../../api/department/departmentList'
import { useNavigate, useSearchParams } from 'react-router-dom'
const DepartmentAddEdit = () => {
  //数据类型 
  interface Option {
    id: number ;
    name: string;
    parent_id:number;
    user:string;
    user_mobile:number | null;
    openid:number|null
    son?: Option[];
}
  // 跳转路由
  const navigate = useNavigate()
  // 路由传参
  const [paramsInfo] = useSearchParams()
    // 调用useRef useRef 返回一个可变的 ref 对象，且只有一个current属性
    const from: any = useRef()
    // console.log('==========',from);
    
  // 调用接口请求
  useEffect(() => {
    getList()//部门列表接口
    departmentShowInfo()//更具id查询数据接口
  }, [])
  // 父级部门的数据展示
  const fieldNames: any = { label: 'name', value: 'id', children: 'son' }
  // 父级部门的数据
  const [options, setoPtions] = useState<Array<Option>>()

  // 请求父级部门的数据
  const getList = async () => {
    const res = await departmentList({})
    // console.log(res);
    setoPtions(res.data)
  }

  // 选择父级部门
  const onChange = (value: any[]) => {
    // console.log(value);
  };

  // 添加接口
  const departmentAddInfo = async (params: any) => {
    const res: any = await departmentAdd(params)
    // console.log(res);
    if (res.code === '00000') {
      message.success('添加成功');
      navigate('/index/DepartmentList')
    } else {
      message.error(res.msg)
    }
  }

  // 更具id渲染修改数据
  const departmentShowInfo =async()=>{
    const res:any = await departmentShow({
      id:paramsInfo.get('id')
    })
    // console.log(res);
    if (res.code === "00000") {
      // setFieldsValue方法 设置表单的值可以更改form store 中的数据
      from.current.setFieldsValue(res.data)
   }
  }

  // 修改接口
  const departmentEditInfo = async (InfoForm:any)=>{
    const res:any = await departmentEdit(InfoForm)
    console.log(res);
    if (res.code === '00000') {
      message.success('修改成功');
      navigate('/index/DepartmentList')
    } else {
      message.error(res.msg)
    }
  }

  // 输入东西的时候打印成功
  const onFinish = (values: any) => {
    // console.log('Success:', values);
    if (paramsInfo.get('id')) {
      const InfoForm = {
        id: Number(paramsInfo.get('id')),
        formdata: {
          name: values.name,
          parent_id: values.parent_id,
          user: values.user,
          user_mobile: values.user_mobile,
          openid: Number(values.openid)
        }
      }
      console.log(InfoForm);
      departmentEditInfo(InfoForm)
    } else {
      // 结构出部门parent_id拿到数据
      const params = { ...values, parent_id: values.parent_id >= 1 ? values.parent_id[values.parent_id.length - 1] : 0 }
      // console.log(params);
      departmentAddInfo(params)
    }
  };

  // 不输入东西的时候打印失败
  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
    message.error('请填写内容');
  };

  //Form.useForm() 创建的 form 控制实例 
  const [form] = Form.useForm();
  // 重置
  const onReset = () => {
    // resetFields方法可以重置字段
    form.resetFields();
  }
  return (<>
    <div className="Add">
      {
        paramsInfo.get('id') ? <h3>修改</h3> : <h3>添加</h3>
      }

      {/* 添加内容 */}
      <div className='add_input'>
        <Form
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 450 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
          form={form}
          ref={from}
        >
          <Form.Item
            label="选择父级部门"
            name="parent_id"
          >
            <Cascader fieldNames={fieldNames} options={options} onChange={onChange} placeholder="请选择" />
          </Form.Item>

          <Form.Item
            label="部门名称"
            name="user"
            rules={[{ required: true, message: '请输入节点名称' }]}
          >
            <Input placeholder="请选择部门名称" />
          </Form.Item>

          <Form.Item
            label="负责人名称"
            name="name"
            rules={[{ required: true, message: '请输入添加人名称' }]}
          >
            <Input placeholder="请选择负责人名称" />
          </Form.Item>

          <Form.Item
            label="负责人手机号"
            name="user_mobile"
            rules={[{ required: true, message: '手机号不能为空' }]}
          >
            <Input placeholder="请选择负责人手机号" />
          </Form.Item>

          <Form.Item
            label="openid"
            name="openid"
            rules={[{ required: true, message: 'openid必填' }]}
          >
            <Input placeholder="请选择负责人手机号" />
          </Form.Item>
          <Form.Item className='button_item'>
            <Button onClick={onReset} style={{ backgroundColor: '#909399', color: '#fff' }}>
              重置
            </Button>
            {/* 通过 form.submit 方法调用表单提交功能 */}
            {
              paramsInfo.get('id') ? <Button type="primary" htmlType="submit">
                修改
              </Button> :
                <Button type="primary" htmlType="submit">
                  添加
                </Button>
            }

          </Form.Item>
        </Form>
      </div>
    </div>
  </>);
}

export default DepartmentAddEdit;